package com.woniu.repaircenter.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.exception.XinanException;
import com.woniu.repaircenter.models.dto.RepairMaterialDTO;
import com.woniu.repaircenter.models.param.AddRepairMaterialParam;
import com.woniu.repaircenter.service.mapper.RepairMaterialMapper;
import com.woniu.repaircenter.service.model.HousingMaterial;
import com.woniu.repaircenter.service.model.RepairMaterial;
import com.woniu.repaircenter.service.service.HousingMaterialService;
import com.woniu.repaircenter.service.service.RepairMaterialService;
import com.woniu.utils.EnumException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 维修材料表 服务实现类
 * </p>
 *
 * @author 吕雨泽
 * @since 2024年12月06日
 */
@Service
public class RepairMaterialServiceImpl extends ServiceImpl<RepairMaterialMapper, RepairMaterial> implements RepairMaterialService {

    @Autowired
    private RepairMaterialMapper repairMaterialMapper;

    @Autowired
    private HousingMaterialService housingMaterialService;

    /**
     * 添加维修材料
     * @param addRepairMaterialParams 包含待添加维修材料参数的列表
     * @param userName              操作用户名
     * @return 成功添加的记录数
     * @throws XinanException 如果库存不足或其他错误发生
     */
    @Override
    @Transactional
    public Integer addRepairMaterial(List<AddRepairMaterialParam> addRepairMaterialParams, String userName) throws XinanException {
        // 获取当前日期字符串
        String date = LocalDate.now().toString();
        // 将 AddRepairMaterialParam 列表转换为 RepairMaterial 列表
        List<RepairMaterial> repairMaterials = BeanUtil.copyToList(addRepairMaterialParams, RepairMaterial.class);
        for (RepairMaterial repairMaterial : repairMaterials) {
            // 查询仓库中的材料信息
            HousingMaterial housingMaterial = housingMaterialService.seatateHousingMaterial(repairMaterial.getMaterialCode());
            // 检查库存是否足够
            if (housingMaterial.getInventory() < repairMaterial.getCount()||repairMaterial.getCount()<0) {
                throw new XinanException(EnumException.MATERIAL_INVENTORY_INSUFFICIENT);
            }
            // 更新仓库中的库存数量
            housingMaterialService.updateHousing(repairMaterial.getMaterialCode(), repairMaterial.getCount());
            // 设置创建时间和创建人
            repairMaterial.setCreateDate(date);
            repairMaterial.setCreateUser(userName);
            //原始数量
            repairMaterial.setExpand1(repairMaterial.getCount().toString());
        }
        try {
            // 插入所有维修材料记录
            Integer insertedCount = repairMaterialMapper.insertAll(repairMaterials);
            return insertedCount;
        } catch (Exception e) {
            // 抛出自定义异常，表示插入失败
            throw new XinanException(EnumException.MATERIAL_INSERT_FAILED);
        }
    }

    /**
     * 更新维修材料
     * @param addRepairMaterialParams 包含待更新维修材料参数的列表
     * @param userName              操作用户名
     * @return 成功更新的记录数
     * @throws XinanException 如果更新过程中发生错误
     */
    @Override
    @Transactional
    public Integer updateRepairMaterial(List<AddRepairMaterialParam> addRepairMaterialParams, String userName) throws XinanException {
        // 将 AddRepairMaterialParam 列表转换为 RepairMaterial 列表
        Integer updatedCount = 0;
        List<RepairMaterial> repairMaterials = BeanUtil.copyToList(addRepairMaterialParams, RepairMaterial.class);
        for (RepairMaterial repairMaterial : repairMaterials) {
            // 查询旧的维修材料记录
            RepairMaterial oldRepairMaterial = repairMaterialMapper.selectRepairMaterial(repairMaterial.getMaterialCode(), repairMaterial.getRepairNum());
            if (repairMaterial.getCount()>oldRepairMaterial.getCount()||repairMaterial.getCount()<0) {
                throw new XinanException(EnumException.INVALID_PARAMETER);
            }
            // 更新仓库中的库存数量
            housingMaterialService.updateHousingInventory(repairMaterial.getMaterialCode(), repairMaterial.getCount());
            // 计算新的库存变化量
            Integer countChange = oldRepairMaterial.getCount()-repairMaterial.getCount() ;
            // 更新维修材料的数量
            repairMaterial.setCount(countChange);
            Integer integer = repairMaterialMapper.updateAll(repairMaterial.getMaterialCode(), repairMaterial.getRepairNum(), countChange);
            updatedCount += integer;
        }
        return updatedCount;
    }

    /**
     * 根据材料编号查询所有维修材料
     * @param materialCode 材料编号
     * @return 维修材料 DTO 列表
     */
    @Override
    public List<RepairMaterialDTO> selectAll(String materialCode) throws XinanException{
        if (materialCode == null||materialCode.equals("")) {
            throw new XinanException(EnumException.INVALID_PARAMETER);
        }
        // 查询所有符合条件的维修材料记录
        List<RepairMaterial> repairMaterials = repairMaterialMapper.selectListRepair(materialCode);
        // 如果存在记录，则将其转换为 DTO 列表并返回；否则返回空列表
        if (repairMaterials != null && !repairMaterials.isEmpty()) {
            return BeanUtil.copyToList(repairMaterials, RepairMaterialDTO.class);
        }
        return Collections.emptyList();
    }

    /**
     * 根据维修单号查询维修材料
     * @param repairNum 维修单号
     * @return 维修材料 DTO 列表
     */
    @Override
    public List<RepairMaterialDTO> selectByRepairNum(String repairNum) {
        // 查询所有符合条件的维修材料记录
        List<RepairMaterialDTO> repairMaterials = repairMaterialMapper.selectListRepairNum(repairNum);
        // 如果存在记录，则将其转换为 DTO 列表并返回；否则返回空列表
        if (repairMaterials != null && !repairMaterials.isEmpty()) {
            return repairMaterials;
        }
        return Collections.emptyList();
    }
}
